/**
 * Created by adrain on 2016/3/10.
 */

;(function($){
    var LightBox = function(settings){
        var self = this;
        this.settings = {
            speed:500,
            maxWidth:1100,
            maxHeight:800
        };
        $.extend(this.settings,settings || {});

        //创建遮罩和弹出框
        this.popupMask = $('<div class="popup-mask">');
        this.popupWin = $('<div class="popup note-popup" >');

        //保存body
        this.bodyNode = $(document.body);

        //渲染剩余的DOM,并且插入到BODY
        this.renderDOM();

        this.picViewArea = this.popupWin.find('div.popupPicBox');//图片预览区域
        this.popupPic = this.popupWin.find('img.popupPicImg');//图片
        this.nextBtn = this.popupWin.find('div.note-popup-next-btn');
        this.prevBtn = this.popupWin.find('div.note-popup-prev-btn');
        this.closeBtn = this.popupWin.find('[data-action="close"]');



        //准备开发事件委托，获取组数据
        this.groupName = null;
        this.groupData=[];//放置同一组数据
        this.bodyNode.delegate('*[data-role=lightbox]','click',function(e){
            //阻止事件冒泡
            e.stopPropagation();
            //获取当前的组名
            var currentGroupName = $(this).attr('data-group');

            if(currentGroupName != self.groupName ){

                self.groupName = currentGroupName;
                //根据当前组名获取同一级数据
                self.getGroup();
            };

            //初始化弹出
            self.initPopup($(this));

        });

        //关闭弹出
        this.popupMask.on('click',function(){
            $(this).fadeOut();
            self.popupWin.fadeOut();
            self.clear=false;
        });
        this.closeBtn.on('click',function(){
            self.popupMask.fadeOut();
            self.popupWin.fadeOut();
            self.clear=false;
        });

        //弹出层的上下切换按钮绑定事件
        this.flag=true;
        this.nextBtn.on('click',function(e){
                e.stopPropagation();
                if(!$(this).hasClass('disabled') && self.flag){
                    self.flag=false;
                    self.goto('next');
                };
            });
        this.prevBtn.on('click',function(e){
                e.stopPropagation();
                if(!$(this).hasClass('disabled') && self.flag){
                    self.flag=false;
                    self.goto('prev');
                };
            });
        //绑定窗口调整事件
        var timer = null;
        this.clear = false;
        $(window).resize(function(){
            if(self.clear){
                window.clearTimeout(timer);
                timer = window.setTimeout(function(){
                    self.loadPicSize(self.groupData[self.index].src);
                },500);
            };
        }).keyup(function(e){
            if(self.clear) {
                var keyValue = e.which;
                if (keyValue == 38 || keyValue == 37) {
                    self.prevBtn.click();
                } else if (keyValue == 39 || keyValue == 40) {
                    self.nextBtn.click();
                }
                //console.log(e.which);
            };
        });
    };

    LightBox.prototype = {
        goto:function(dir){
            if(dir === 'next'){
                //this.groupData
                //this.index
                this.index++;
                if(this.index >= this.groupData.length-1){
                    this.nextBtn.addClass('disabled');
                };
                if(this.index != 0){
                    this.prevBtn.removeClass('disabled');
                };
                var src = this.groupData[this.index].src;
                this.loadPicSize(src);


            }else if(dir === 'prev'){
                this.index--;
                if(this.index <= 0){
                    this.prevBtn.addClass('disabled');
                };
                if(this.index != this.groupData.length-1){
                    this.nextBtn.removeClass('disabled');
                };
                var src = this.groupData[this.index].src;
                this.loadPicSize(src);
            };
        },
        loadPicSize:function(sourceSrc){
            var self = this;
            self.popupPic.css({
                    width:'auto',
                    height:'auto'
                }).hide();

            self.popupPic.attr('src',sourceSrc);
            this.preLoadImg(sourceSrc,function(){

                var picWidth = self.popupPic.width(),
                    picHeight = self.popupPic.height(),
                    picScale = picWidth/picHeight;

                if( picWidth > self.settings.maxWidth){
                    picWidth=self.settings.maxWidth;
                    picHeight=picWidth*picScale;
                };
                if(picHeight > self.settings.maxHeight){
                    picHeight=self.settings.maxHeight;
                    picWidth=picHeight*picScale;
                };

                //console.log(picWidth + ': '+ picHeight)
                self.changePic(picWidth,picHeight);

            });
        },
        changePic:function(width,height){
            var self = this,
                winWidth = $(window).width(),
                winHeight = $(window).height();

            //如果图片的宽高大于浏览器视口的宽高比例，就看一下是否溢出

            var scale = Math.min(winWidth/width,winHeight/height,1);

            width = width * scale;
            height = height * scale;

            this.picViewArea.animate({
                    width:width,
                    height:height
                },self.settings.speed);
            this.popupWin.animate({
                    width:width,
                    height:height,
                    marginLeft:-(width/2),
                    marginTop:-(height/2)
                },self.settings.speed,function(){
                    self.popupPic.css({
                        width:width,
                        height:height
                    }).fadeIn();
                    self.flag=true;
                    self.clear=true;
                });

        },
        preLoadImg:function(src,callback){
            var img = new Image();
            if(!!window.ActiveXObject){//如果是ie浏览器
                img.onreadystatechange = function(){
                    if(this.readyState == 'complete'){
                        callback();
                    };
                };
            }else {
                img.onload = function(){
                    callback();
                };
            };
            img.src = src;
        },
        initPopup:function(currentObj){
            var self      = this,
                sourceSrc = currentObj.attr('data-source'),
                currentId = currentObj.attr('data-id');

            this.showMaskAndPopup(sourceSrc,currentId);
        },
        showMaskAndPopup:function(sourceSrc,currentId){
            var self = this;
            this.popupPic.hide();
            this.popupMask.fadeIn();

            //保存当前视口的宽高
            var winWidth = $(window).width(),
                winHeight = $(window).height();

            this.picViewArea.css({
                    width:winWidth/2,
                    height:winHeight/2
                });

            this.popupWin.fadeIn();

            var viewHeight = winHeight/2;
            this.popupWin.css({
                    width:winWidth/2,
                    height:winHeight/2,
                    marginLeft:-(winWidth/2)/2,
                    marginTop:-winHeight
                }).animate({
                    marginTop:-viewHeight/2
                },self.settings.speed,function(){
                    //加载图片
                    self.loadPicSize(sourceSrc);
                });

            //根据当前点击的元素ID获取在当前级别的索引
            this.index = this.getIndexOf(currentId);

            var groupDataLength = this.groupData.length;
            if(groupDataLength>1){
                if(this.index === 0){
                    this.prevBtn.addClass('disabled');
                    this.nextBtn.removeClass('disabled');
                }else if(this.index === groupDataLength-1){
                    this.prevBtn.removeClass('disabled');
                    this.nextBtn.addClass('disabled');
                }else {
                    this.prevBtn.removeClass('disabled');
                    this.nextBtn.removeClass('disabled');
                }
            }


        },
        getIndexOf:function(currentId){
            var index = 0;
            $(this.groupData).each(function(i){
                index = i;
                if(this.id === currentId){
                    return false;
                }
            });
            return index;
        },
        getGroup:function(){
            var self = this;
            //根据当前的组别名称，获致页面中所有相同级别的对象
            var groupList = this.bodyNode.find('*[data-group="'+this.groupName+'"]');

            //清空数组数据
            self.groupData.length=0;

            groupList.each(function(){
                self.groupData.push({
                    src:$(this).attr('data-source'),
                    id:$(this).attr('data-id')
                });
            });

        },
        renderDOM:function(){
            var strDom = '<div class="popupPicBox">'+
                         '<span data-action="close" class="icon32 icon-colse"></span>'+
                         //'<div class="note-popup-btn note-popup-prev-btn">'+
                         //'<span class="prevNext-btn"></span>'+
                         //' </div>'+
                         //'   <div class="note-popup-btn note-popup-next-btn">'+
                         //'<span class="prevNext-btn"></span>'+
                         //'</div> '+
                         '<img class="popupPicImg" src="../../images/product/promo-1.jpg">'+
                         '</div>';

            //插入到this.popup@in
            this.popupWin.html(strDom);
            //把遮罩和弹出层插入到body
            this.bodyNode.append(this.popupMask,this.popupWin);

        }
    };

    window['LightBox'] = LightBox;

})(jQuery);























